const configGlobal = require('./config/config_global.js');
var util = require('./utils/function.js');

App({

    globalData: {
        userInfo: null,         //微信用户信息
        openId: '',             //用户微信标识
        session_key: '',        // session_key标识

    },

    onLaunch: function (options) {
        console.log('App onLaunch');
        var that = this;

        // 初始化登录-此处可不写，留在需要用户授权登录的时候再加上
        var session = that.getSession();
        if (!session) {
            that.getUserInfo();
        } else {
            that.setGlobalData(session);
        }

    },

    onShow: function (options) {
        console.log('App onShow');
        var that = this;

        // 每次使用，都记录下使用时间--如无此需求，可删除
        var session = that.getSession();
        if (!session) {
            that.getUserInfo();
        } else {
            var openId = that.globalData.openId;
            that.putLoginLog(openId);
        }
    },

    onHide: function () {
        console.log('App onHide');
        var that = this;

    },

    onError: function(msg) {
        console.log(msg);

    },

    /**
     * 公共变量赋值
     */
    setGlobalData: function(session) {
        console.log('App setGlobalData');
        var that = this;

        that.globalData.userInfo = session.userInfo;
        that.globalData.openId = session.openId;
        that.globalData.session_key = session.session_key;
    },

    /**
     * 清除公共变量
     */
    clearGlobalData: function() {
        console.log('App setGlobalData');
        var that = this;

        that.globalData.userInfo = null;
        that.globalData.openId = '';
        that.globalData.session_key = '';
    },


    /**
     * 重新授权
     */
    getAuthorize: function() {
        console.log('App getAuthorize');
        var that = this;

        that.getUserInfo();
        //  that.openSetting();
    },

    /**
     * 取出本地保存的session，并判断是否有效，若有效则返回session内容
     */
    getSession: function() {
        console.log('App getSession');
        var that = this;

        var session = null;
        try {
            session = wx.getStorageSync('session');
            if (session) {
                wx.checkSession({
                    success: function(res) {
                        console.log('登录态未过期');
                        that.setGlobalData(session);
                    },
                    fail: function(res) {
                        console.log('登录态过期');
                        session = null;
                        that.clearGlobalData();
                    }
                });
            } else {
                console.log("no session！");
                session = null;
                that.clearGlobalData();
            }
        } catch (e) {}

        return session;
    },

    /**
     * 提示是否授权登录
     */
    getUserInfo: function() {
        console.log('App getUserInfo');
        var that = this;

        //调用登录接口
        wx.login({
            success: function(res) {
                var code = res.code;

                wx.getUserInfo({
                    lang: 'zh_CN',
                    success: function(res) {
                        console.log('得到用户登录时客户端返回：', res);

                        //将用户信息提交到服务器上去
                        wx.request({
                            url: configGlobal.request_url + "/_WxaappApiServer/getUserInfo",
                            method: 'GET',
                            data: {
                                code: code;
                                signature: res.signature;
                                iv: res.iv;
                                encryptData: res.encryptData;
                                encryptedData: res.encryptedData;
                                rawData: res.rawData;
                            },
                            header: {
                                'Content-Type': 'application/json; charset=utf-8'
                            },
                            success: function(res) {

                                console.log('得到用户登录时服务器返回：', res);

                                //这儿的判断条件要自定义的 对userInfo重新赋值
                                if (res.data) {
                                    var session = res.data.data;
                                    console.log('session:', session);
                                    //放到公共变量中
                                    that.setGlobalData(session);

                                    //写到本地中来
                                    try {
                                        wx.setStorageSync('session', session);
                                        res = true;
                                    } catch (e) {}

                                } else {
                                    console.log('获取失败！');
                                }

                            },
                            fail: function(res) {
                                console.log('获取失败:', res);
                            }
                        });
                    },
                    fail: function(res) {
                        console.log("不同意授权！");
                        that.openSetting();
                    },
                    complete: function(res) {},
                })
            },
            fail: function(res) {
                console.log("登录失败！");
            },
            complete: function(res) {},
        });
    },

    /**
     * 打开配置页面，让用户配置授权登录
     */
    openSetting: function() {
        console.log('App openSetting');
        var that = this;

        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.userInfo']) {
                    wx.showModal({
                        title: '',
                        content: '请先完成授权！在设置页面中勾选“用户信息”选项，否则部分功能将受限。',
                        showCancel: true,
                        confirmText: '前去设置',
                        confirmColor: '#004b97',
                        success: function(res) {
                            console.log(res);

                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.openSetting({
                                    success: (res) => {
                                        res.authSetting = {
                                            'scope.userInfo': true,
                                        };
                                    },
                                    complete: function(res) {
                                        that.openSetting();
                                    },
                                })
                            }

                            if (res.cancel) {
                                console.log('用户点击取消');
                                wx.showToast({
                                    title: '授权失败，部份功能受限！',
                                    duration: 2000
                                });
                            }

                            if (!res.confirm && !res.cancel) {
                                console.log('安桌手机中用户点击蒙层');
                                that.openSetting();
                            }

                        }
                    });

                } else {
                    that.getUserInfo();
                }
            }
        })
    },

    /**
     * 将登录状态提交到服务器
     */
    putLoginLog: function() {
        console.log('App putLogin');
        var that = this;

        //向服务器提交一次登录信息
        wx.request({
            url: configGlobal.request_url + "/_WxaappApiServer/putLoginLog",
            method: 'GET',
            data: {
                openId: that.globalData.openId
            },
            header: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {}
        });
    },

});
